<template>
  <div v-loading="pageLoading" class="create-container">
    <ListTab v-model="activeId" :show-header="false" :tabs="tabList" class="box-shadow" @tabClick="tabClick" >
      <div :style="`min-width:${!isFixed ? '437px': '347px'}`" class="flex-center right-box" >
        <div class="back-btn" @click="toBack">
          <i class="icon el-icon-arrow-left"/>
          <!-- <div class="text">{{ formName }}</div> -->
          <div class="text">
            <ToolTip :content="formName" />
          </div>
        </div>
        <div v-if="saveTime" class="save-info">
          <p>已自动保存当前信息</p>
          <p>{{ format(saveTime, 'YYYY/MM/DD HH:mm:ss') }}</p>
        </div>
        <el-button v-if="!isFixed" plain type="primary" class="preview-btn-style" size="small" @click="preview">预览</el-button>
        <el-button v-if="isEdit" :loading="submitLoading" type="primary" size="small" @click="fullDataValid(false)">{{ confirmText }}</el-button>
        <el-button :loading="submitLoading" type="primary" size="small" @click="fullDataValid(true)">
          {{ confirmText }}并返回
        </el-button>
      </div>
    </ListTab>
    <div class="create-content">
      <div class="container">
        <!-- 基本设置 -->
        <BasicSettings
          v-show="activeId === 0"
          ref="basicSettingRef"
          :is-fixed="isFixed"
          :is-edit="isEdit"
          @statusCheck="statusCheck"
          @formNameChange="formNameChange"/>
        <!-- 表单设计 -->
        <FormMake v-show="activeId === 1" v-model="formOptions" :fixed-id="fixedId" :process-list="customProcessList" @statusCheck="statusCheck" @quoteProcess="quoteProcess" />
        <!-- 流程设计 -->
        <ProcessCreateModule
          v-show="activeId === 2"
          ref="processCreateModuleRef"
          :event-names="eventNames"
          :is-fixed="isFixed"
          :fixed-id="fixedId"
          :process-list="processList"
          :custom-form-list="formOptions.list"
          @statusCheck="statusCheck" />
        <!-- 高级设置 -->
        <AdvancedSettings
          v-show="activeId === 3"
          ref="advancedSettingRef"
          :is-fixed="isFixed"
          :is-admin="isAdmin"
          :module-id="id"
          :form-list="formOptions.list"
          :advanced-options="advancedOptions"
          :sync-status="syncStatus"
          @statusCheck="statusCheck"
          @syncData="syncData"
          @eventNameChange="eventNameChange"/>
      </div>
    </div>
    <Preview ref="previewRef" />
  </div>
</template>

<script>
import ListTab from '@/components/ListTab';
import FormMake from './components/formMake/formMake';
import Preview from './components/formMake/preview';
import BasicSettings from './components/basicSettings';
import AdvancedSettings from './components/advancedSettings';
import ProcessCreateModule from './model/processCreate';
import { getApprovalTemplate } from '@/api/approvalModule';
import { createProcess, editProcess, syncData, getSyncStatus } from '@/api/process';
import ElMessage from '@/utils/message';
import formMakeMixins from '@/views/legal/process/mixins/formMake.js';
import { setLinkStatistics } from './mixins/linkFormUtils';
import { mapState } from 'vuex';
import { forEachFormOptions, isNumberType } from '@/utils/formMakeUtils.js';
import { setTagFormula } from '@/views/legal/process/components/formMake/utils/index.js';
import { EventBus } from '@/utils/eventBus';
import { BPDepartment } from '@/utils/const/process';
import { showModal } from '@/utils/message';
import { format } from '@/filters/date';
// api
import { processManagementList } from '@/api/legal';
import { getRoleGroups } from '@/api/user';
import { getBPList } from '@/api/BPManage';
import { createLocalStorage } from '@/utils/storage';

// 缓存 60分钟
const ss = createLocalStorage({ expire: 60 * 60 });
export default {
  components: {
    ListTab,
    FormMake,
    BasicSettings,
    AdvancedSettings,
    Preview,
    ProcessCreateModule
  },
  mixins: [formMakeMixins],
  data() {
    return {
      id: '',
      fixedId: '', // 表单固定id
      activeId: 0,
      submitLoading: false,
      initToProcess: true,
      isEdit: false,
      isFixed: false, // 固定表单
      pageLoading: false,
      formName: '', // 审批名称
      formOptions: { // 自定义表单配置
        list: [],
        config: {
          labelWidth: 100,
          labelPosition: 'right',
          keyToFormula: {}, // 公式字段的映射表（被引用的字段: 引用它的公式字段）
          formValidate: [], // 发起审批验证
          fieldCondition: [] // 字段显示条件
        }
      },
      processList: [],
      customProcessList: [],
      eventNames: [], // 高级设置事件名称
      postFollowerData: {}, // 人员和职位映射关系
      adminId: '', // 流程管理员id
      basicStatus: false,
      formStatus: false,
      processStatus: false,
      advancedStatus: false,
      advancedOptions: {},
      syncStatus: [], // 数据表的同步状态
      syncDataItem: null, // 数据同步的数据
      timer: null, // 数据同步定时器
      saveTimer: null, // 数据保存定时器
      saveTime: null, // 保存时间
      getFormTimeOut: null,
      isInit: true
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'widgetTypes': state => state.formMake.widgetTypes
    }),
    tabList() {
      // isDot: 是否显示流程存在必填项未填写提示
      const baseList = [
        { id: 0, name: '基本设置', isDot: this.basicStatus },
        { id: 1, name: '表单设计', isDot: this.formStatus },
        { id: 2, name: '流程设计', isDot: this.processStatus },
        { id: 3, name: '高级设置', isDot: this.advancedStatus }
      ];
      if (this.isFixed) { // 固定表单删除表单设计tab
        baseList.splice(1, 1);
      }
      return baseList;
    },
    confirmText() {
      return this.isEdit ? '保存' : '发布';
    },
    isAdmin() {
      return this.userInfo.id === this.adminId;
    }
  },
  watch: {
    '$store.state.process.approverDrawer': {
      handler: function(val) {
        if (!val) this.statusCheck();
      }
    }
  },
  created() {
    const { isFixed } = this.$route.query;
    const id = this.$route.params.id;
    this.isFixed = !!isFixed;
    if (id) {
      this.isEdit = true;
      this.id = Number(id);
      this.getData(this.id);
      this.setTimer(this.id);
    } else {
      this.isEdit = false;
      this.initAllWidget();
    }
    this.getProcessList();
    this.queryRoleGroups();
    this.queryBPList();
    this.$store.dispatch('setSelectWidget', null);
    EventBus.$on('formOptionsChange', (data) => {
      this.statusCheck();
    });
  },
  mounted() {
    this.getFormTimeOut = setTimeout(() => {
      this.getFormData();
    }, 500);
  },
  beforeDestroy() {
    this.clearTimer();
    clearTimeout(this.getFormTimeOut);
    this.getFormTimeOut = null;
  },
  methods: {
    format,
    getData(id) {
      this.pageLoading = true;
      getApprovalTemplate({ id, isEdit: true }).then(res => {
        if (res.code === 200) {
          // 获取详情数据
          this.$refs['basicSettingRef'].setData(res.data.baseOptions); // 设置基本设置的数据
          this.pageLoading = false;
          const { formOptions, processOptionsDetail, advancedOptions, adminId } = res.data;
          this.$nextTick(() => {
            this.$refs['processCreateModuleRef'].setDefaultData(processOptionsDetail); // 设置流程设计的数据
            this.$refs['advancedSettingRef'].setData(advancedOptions, processOptionsDetail.type); // 设置高级设置的数据
          });
          if (!this.isFixed) {
            if (!formOptions.config.keyToFormula) formOptions.config.keyToFormula = {};
            this.formOptions = formOptions;
            this.advancedOptions = advancedOptions;
            this.$refs['advancedSettingRef'].setConfigField(formOptions.list); // 设置配置相关字段
            this.getEventNames(advancedOptions.event);
            this.$nextTick(() => {
              this.statusCheck();
              this.initAdvancedCheck(advancedOptions);
            });
          }
          this.isFixed && this.storeAllFixedDeptSelectFields(res.data.processOptionsDetail && res.data.processOptionsDetail.type);
          this.adminId = adminId;
          this.fixedId = res.data.formId;
        }
        this.initAllWidget();
      }).catch(_ => {
        this.pageLoading = false;
      });
    },
    initAdvancedCheck(advancedOptions) {
      this.$nextTick(() => {
        const { list, notice } = advancedOptions;
        let noticeStatus = false;
        let listStatus = false;
        noticeStatus = !notice.length ? true : notice.filter(it => it.isCheck).length < 1;
        const fieldArr = list.field.filter(it => it.isCheck);
        const filterArr = list.filter.filter(it => it.isCheck);
        listStatus = fieldArr.length < 1 && filterArr.length < 1;
        this.advancedStatus = noticeStatus && listStatus;
      });
    },
    // tab填写状态提示
    statusCheck() {
      const { name } = this.$route;
      if (name === 'ContractProcessEditCustom') {
        if (this.formOptions.list.length) {
          this.handleStatusCheck();
        }
      } else if (name === 'ContractProcessCreateCustom') {
        this.handleStatusCheck();
      }
      this.saveCache();
    },
    saveCache: _.throttle(function() {
      if (!this.isInit) {
        this.setFormData();
      }
      this.isInit = false;
    }, 2000),
    syncData(formItem) {
      this.syncDataItem = formItem;
      this.fullDataValid(false);
    },
    beginSyncData(moduleId) { // 传的是formId
      const data = {
        moduleId: moduleId,
        ...this.syncDataItem
      };
      syncData(data).then(res => {
      }).catch(err => {
        console.log(err);
      });
      if (!this.timer) {
        this.getSyncStatus(moduleId);
        this.setTimer(moduleId);
      }
    },
    // 每隔一段时间去查询是否在同步数据
    setTimer(moduleId, time = 1500) {
      this.timer = setInterval(() => {
        this.getSyncStatus(moduleId);
      }, time);
    },
    // 页面销毁清除定时器
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    getFormData() {
      const data = ss.get('customProcessData');

      if (data && ((this.id && data.id === this.id) || (!this.id && !data.id))) {
        showModal('请确认是否恢复上次所填数据？', '', { closeOnClickModal: false }).then(_ => {
          ss.remove('customProcessData');
          // 获取详情数据
          this.$refs['basicSettingRef'].setData(data.baseOptions); // 设置基本设置的数据
          this.pageLoading = false;
          // const { formOptions, processOptionsDetail, advancedOptions, adminId } = data;
          const { formOptions, advancedOptions, processOptions } = data;
          if (!this.isFixed) {
            if (!formOptions.config.keyToFormula) formOptions.config.keyToFormula = {};
            this.formOptions = formOptions;
            this.advancedOptions = advancedOptions;
            this.$refs['advancedSettingRef'].setConfigField(formOptions.list); // 设置配置相关字段
            this.getEventNames(advancedOptions.event);
            this.$nextTick(() => {
              this.statusCheck();
              this.initAdvancedCheck(advancedOptions);
            });
          }
          if (processOptions) {
            processOptions.processSettingTemplate = processOptions.process;
            this.$nextTick(() => {
              this.$refs['processCreateModuleRef'].setDefaultData(processOptions, 1); // 设置流程设计的数据
              this.$refs['advancedSettingRef'].setData(advancedOptions, processOptions.type); // 设置高级设置的数据
            });
          } else {
            this.$refs['advancedSettingRef'].setData(advancedOptions); // 设置高级设置的数据
          }
          // this.isFixed && this.storeAllFixedDeptSelectFields(data.processOptionsDetail && data.processOptionsDetail.type);
          // this.adminId = adminId;
          this.fixedId = data.formId;
          // this.$forceUpdate();
        });
      }
    },
    setFormData() {
      const params = {};
      params.baseOptions = this.$refs['basicSettingRef'].getBasicInfo(); // 基本设置
      params.processOptions = this.$refs['processCreateModuleRef'].getDetailData(false, false); // 流程设计
      params.advancedOptions = this.$refs['advancedSettingRef'].getAdvancedData(); // 高级设置
      if (!this.isFixed) {
        const formOptions = _.cloneDeep(this.formOptions);
        this.postFollowerData = {};
        this.handleFormOptions(formOptions);
        formOptions.config.postFollowerData = this.postFollowerData;
        this.$refs['advancedSettingRef'].initDataList(this.formOptions.list);// 同步表单设计的变动
        params.formOptions = formOptions; // 表单设计
      }
      if (this.id) {
        params.id = this.id;
      }
      ss.set('customProcessData', params);
      this.saveTime = new Date().getTime();
    },
    // 轮询获取数据同步状态
    getSyncStatus(moduleId) {
      getSyncStatus({ moduleId }).then(res => {
        if (res.code === 200) {
          this.syncStatus = res.data;
          if (!res.data.find(i => i.inSync === 1) || !(res.data && res.data.length)) {
            this.clearTimer();
          }
        }
      }).catch(err => {
        console.log(err);
      });
    },
    handleStatusCheck() {
      this.$nextTick(() => {
        if (this.$refs['basicSettingRef']) {
          this.basicStatus = this.$refs['basicSettingRef'].basicInfo.name === '' || this.$refs['basicSettingRef'].basicInfo.group === '';
        }
        this.validateForBadge();
        if (this.$refs['processCreateModuleRef']) {
          const processOptions = this.$refs['processCreateModuleRef'].getDetailData(false);
          this.processStatus = processOptions === null;
          if (!this.isFixed) {
            this.advancedStatus = this.$refs['advancedSettingRef'].isShowAdvancedDot;
          }
        }
      });
    },
    fullDataValid(goBack = true) {
      this.statusCheck();
      const processOptions = this.$refs['processCreateModuleRef'].getDetailData();
      if (!processOptions) return; // 流程设计
      const promise = [];
      if (this.formOptions) {
        forEachFormOptions(this.formOptions.list, (i) => {
          if (i._isNew) {
            i._isNew = false;
            delete i._isNew;
          }
        });
        // this.$forceUpdate();
      }
      const formOptions = _.cloneDeep(this.formOptions);
      promise.push(this.$refs['basicSettingRef'].validateForm()); // 基本设置
      if (!this.isFixed) {
        this.postFollowerData = {};
        this.handleFormOptions(formOptions);
        formOptions.config.postFollowerData = this.postFollowerData;
        this.$refs['advancedSettingRef'].initDataList(this.formOptions.list);// 同步表单设计的变动
        promise.push(this.validate(formOptions)); // 表单设计
        promise.push(this.$refs['advancedSettingRef'].validateAllSettings()); // 高级设置
      }
      Promise.all(promise).then(() => {
        this.submit(goBack, formOptions);
      }).catch(msg => {
        ElMessage.error(msg);
      });
    },
    submit(goBack = true, formOptions) {
      const params = {};
      params.baseOptions = this.$refs['basicSettingRef'].getBasicInfo(); // 基本设置
      params.processOptions = this.$refs['processCreateModuleRef'].getDetailData(); // 流程设计
      params.advancedOptions = this.$refs['advancedSettingRef'].getAdvancedData(); // 高级设置
      if (!this.isFixed) {
        params.formOptions = formOptions; // 表单设计
      }
      this.submitLoading = true;
      this.isEdit ? this.edit(params, goBack) : this.add(params, goBack);
    },
    add(data, goBack) {
      createProcess(data).then(res => {
        this.submitLoading = false;
        if (res.code === 200) {
          ElMessage.success('创建成功');
          if (this.syncDataItem) {
            this.beginSyncData(res.data.moduleId);
            this.syncDataItem = null;
          }
          goBack && this.toBack();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(_ => {
        this.submitLoading = false;
      });
    },
    edit(data, goBack) {
      data.id = this.id;
      editProcess(data).then(res => {
        this.submitLoading = false;
        if (res.code === 200) {
          ElMessage.success('编辑成功');
          goBack && this.toBack();
          if (this.syncDataItem) {
            this.beginSyncData(this.fixedId);
            this.syncDataItem = null;
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(_ => {
        this.submitLoading = false;
      });
    },
    preview() {
      const formOptions = _.cloneDeep(this.formOptions);
      this.postFollowerData = {};
      this.handleFormOptions(formOptions, true);
      formOptions.config.postFollowerData = this.postFollowerData;
      this.validate(formOptions).then(() => {
        this.$refs.previewRef.open(formOptions);
      }).catch((msg) => {
        ElMessage.error(msg);
      });
    },
    validateForBadge() {
      const formOptions = _.cloneDeep(this.formOptions);
      this.validate(formOptions).then(() => {
        this.formStatus = false;
      }).catch(() => {
        this.formStatus = true;
      });
    },
    // 保存和预览前，先进行验证
    validate(formOptions) {
      return new Promise((resolve, reject) => {
        if (formOptions.list.length === 0) {
          reject('请在表单设计中拖拽添加字段');
          return;
        }
        formOptions.list.forEach(element => {
          this.validateElement(element, reject);
          if (element.type === 'grid' && element.columns.length) {
            element.columns.forEach(j => {
              if (j.list && j.list.length) {
                j.list.forEach(girdElement => {
                  this.validateElement(girdElement, reject);
                });
              }
            });
          } else if (element.type === 'subform') {
            if (element.options.titleLevel) {
              if (element.subform.length) {
                element.subform.forEach(girdElement => {
                  this.validateElement(girdElement, reject);
                });
              }
            } else {
              reject(`请设置${element.name}的标题层级`);
            }
          }
        });
        resolve();
      });
    },
    // 处理提交数据
    handleFormOptions(formOptions) {
      const keyToFormula = {};
      const keyToHightFormula = {};
      const userFollowerData = {};
      const formValueTypes = {};
      forEachFormOptions(formOptions.list, (i) => {
        formValueTypes[i.key] = isNumberType(i) && i.type !== 'formulaInput' ? 'number' : i.type;
        if (i.type === 'post') {
          this.setPostFollowerData(i);
        }
        if (i.type === 'user') {
          this.setUserFollowerData(i, userFollowerData);
        }
        // 设置公式字段和被其引用的字段之间的关系 setKeyToFormula 位置在 ./mixins/formMake.js 中
        if (i.type === 'formulaInput' && i.options.formulaOrigin && !i.options.modeType) {
          this.setKeyToFormula(i, keyToFormula);
        }
        // 有选择类型的字段，去除空的选项
        if (i.options && i.options.options && i.options.options.length) {
          i.options.options = i.options.options.filter(i => i.id || i.id === 0);
        }
        // 设置关联表单的统计字段
        if (i.type === 'linkForm' && i.options.isStatistics && i.subform && i.subform.length) {
          setLinkStatistics(i);
        } else if (i.type === 'linkForm' && !i.options.isStatistics) {
          i.options.statistics = [];
        }
        if (i.type === 'linkForm') {
          i.value = [];
        }
        // 设置每个字段的dataType，接口要用
        if (!i.isSubTable && i.type !== 'input' && i.type !== 'subform' && i.type !== 'grid' && i.type !== 'title' && i.type !== 'linkForm') {
          let valType = typeof i.value;
          if (valType === 'object' && Array.isArray(i.value)) valType = 'array';
          i.options.dataType = valType;
        }
      });
      forEachFormOptions(formOptions.list, (i) => {
        if (i.type === 'formulaInput' && i.options.filterList && i.options.filterList.length) {
          i.options.filterList.forEach(filter => {
            if (filter.filterField && formValueTypes[filter.filterField]) filter.dataType = formValueTypes[filter.filterField];
          });
        }
      });
      formOptions.config.keyToFormula = keyToFormula;
      formOptions.config.keyToHightFormula = keyToHightFormula;
      formOptions.config.userFollowerData = userFollowerData;
    },
    // 设置人员选择组件映射
    setUserFollowerData(data, userFollowerData) {
      if (data.options.userSelectValue && data.options.defaultValue > 4) {
        if (!userFollowerData[data.options.userSelectValue]) {
          userFollowerData[`${data.options.userSelectValue}`] = [];
        }
        userFollowerData[`${data.options.userSelectValue}`].push(data.key);
      }
    },
    // 设置人员选择和职位映射
    setPostFollowerData(data) {
      const currPostValue = {
        key: data.key,
        linkFormKey: data.linkFormKey,
        isMultiple: data.options.isMultiple,
        isSubTable: data.isSubTable
      };
      if (data.options.follower) {
        if (this.postFollowerData[data.options.follower]) {
          this.postFollowerData[data.options.follower].push(currPostValue);
        } else {
          this.postFollowerData[data.options.follower] = [currPostValue];
        }
      }
    },
    eventNameChange(list) {
      this.eventNames = list;
    },
    formNameChange(name) {
      this.formName = name;
      this.statusCheck();
    },
    // 编辑时初始化对流程设计的审批事件赋值
    getEventNames(list) {
      if (Array.isArray(list) && list.length) {
        this.eventNames = list.map(item => {
          return { label: item.name, value: item.id, operate: item.operate, target: item.target };
        });
      }
    },
    toBack() {
      this.$router.push({
        name: 'ContractProcess'
      });
    },
    tabClick(id) {
      this.statusCheck();
      // 设置流程设计的居中，只有第一次进入会调用
      if (id === 2 && this.initToProcess) {
        this.initToProcess = false;
        this.$refs['processCreateModuleRef'].setMiddle(); // 设置流程设计的居中
      }
      if (id === 3) {
        this.$refs['advancedSettingRef'].initDataList(this.formOptions.list);
      }
    },
    validateElement(element, reject) {
      if (!element.name) {
        reject('请输入字段名称');
        return;
      }
      if (element.type === 'select' || element.type === 'radio' || element.type === 'checkbox') {
        const options = element.options.options;
        const emptyArr = options.filter(it => !it.id);
        if (!options || options.length === 0 || !!emptyArr.length) {
          reject(`请设置${element.name}的选项`);
          return;
        }
      }
      if (element.type === 'formulaInput' && !element.options.modeType) {
        const options = element.options.formulaOrigin;
        if (!options || options.length === 0) {
          reject(`请设置${element.name}的公式`);
          return;
        }
      }
      if (element.type === 'linkForm' || element.type === 'subform') {
        if (!element.subform || element.subform.length === 0) {
          reject(`请设置${element.name}的字段`);
          return;
        }
        if (element.options.isAutoStorage && !element.options.storageMaxLength) {
          reject('请输入最多存储条数');
          return;
        }
        if (!element.options.titleLevel) {
          reject(`请设置${element.name}的标题层级`);
          return;
        }
      }
      if (element.type === 'title' && !element.options.titleLevel) {
        reject(`请设置${element.name}的标题层级`);
        return;
      }
      if (element.type === 'textarea' || element.type === 'input') {
        if (element.options.dataType === 'number') {
          const numberRange = element.options.numberRange;
          if (numberRange.length !== 2 || (!numberRange[0] && numberRange[0] !== 0) || (!numberRange[1] && numberRange[1] !== 0)) {
            reject(`请设置${element.name}的数值范围限制`);
            return;
          }
          if (!element.options.precision && element.options.precision !== 0) {
            reject(`请设置${element.name}的小数位数`);
            return;
          }
        }
        const options = element.options.options;
        if (element.options.defaultType === 1 && (!options || options.length === 0)) {
          reject(`请设置${element.name}的选项`);
          return;
        }
        if (!element.options.maxlength) {
          reject(`请设置${element.name}的字符长度限制`);
          return;
        }
        if (element.type === 'textarea' && !element.options.rows) {
          reject(`请设置${element.name}的可见行数`);
          return;
        }
      }
      if (element.type === 'workflowId' && !element.options.prefix) {
        reject(`请设置${element.name}的前缀`);
        return;
      }
    },
    quoteProcess(val) {
      /**
       * 引用时要做以下几件事情
       * 1、重新设置所有字段的 key，包括子表单字段、关联表单字段里面的父节点key (linkFormKey)
       * 2、建立旧的key与新的key的映射结构 oldkeyToNewkey
       * 3、通过 oldkeyToNewkey 更新公式字段里面所引用字段的key
       * 4、运行高级设置的 setConfigField 进行高级设置里面字段的初始化
       * 5、初始化高级设置里面列表字段
       * 6、初始化高级设置里面事件目标字段
       * 7、初始化高级设置里面通知模版字段
       * 8、运行 initAllWidget 进行整体初始化
       */
      this.getTemplateData(val);
    },
    getTemplateData(id) {
      getApprovalTemplate({ id }).then(res => {
        if (res.code === 200) {
          // 获取详情数据
          const oldkeyToNewkey = new Map(); // 同一个字段的旧的key：新的key
          const { formOptions } = res.data;
          const newKeys = [];
          forEachFormOptions(formOptions.list, (element) => {
            // 保险起件，判断一下key是否重复，因为遍历设置key的话，时间戳是一样的，这样就增加了重复的风险
            let key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
            if (newKeys.includes(key)) key = key + Math.ceil(Math.random() * 99999);
            newKeys.push(key);
            oldkeyToNewkey.set(element.key, key);
            element.key = key;
          });
          /**
           * 更新各种字段里面有引用关系的字段
           */
          forEachFormOptions(formOptions.list, (element) => {
            // 更新用户字段引用关系
            if (element.type === 'user' && element.options.userSelectValue) {
              if (oldkeyToNewkey.has(element.options.userSelectValue)) {
                element.options.userSelectValue = oldkeyToNewkey.get(element.options.userSelectValue);
              }
            }
            // 更新子表单字段里面统计字段的key
            if (element.type === 'subform') {
              if (element.options.statistics && element.options.statistics.length) {
                element.options.statistics = element.options.statistics.map(j => {
                  return oldkeyToNewkey.get(j);
                });
              }
              if (element.value && element.value.length) {
                const newValue = [];
                // 如果子表单里面原来有默认值，则通过 oldkeyToNewkey 把旧的value转换成新的value，最后进行替换
                element.value.forEach(subformVal => {
                  const newObj = {};
                  Object.keys(subformVal).forEach(oldValKey => {
                    if (oldkeyToNewkey.has(oldValKey)) {
                      newObj[oldkeyToNewkey.get(oldValKey)] = subformVal[oldValKey];
                    }
                  });
                  newValue.push(newObj);
                });
                this.$set(element, 'value', newValue);
              }
            }
            if (element.type === 'post' && element.options.follower && oldkeyToNewkey.has(element.options.follower)) {
              element.options.follower = oldkeyToNewkey.get(element.options.follower);
            }
            // 更新公式字段里面被引用的字段的key
            if (element.type === 'formulaInput' && element.options.formulaOrigin) {
              let tagFormula = '';
              element.options.formulaOrigin.forEach(j => {
                if (j.type !== 'math' && j.type !== 'number') {
                  // 从 oldkeyToNewkey 中获取所对应的新 key，进行更新
                  if (oldkeyToNewkey.has(j.key)) {
                    j.key = oldkeyToNewkey.get(j.key);
                  }
                  // 更新子表单和关联表单字段的父节点key
                  if (j.linkFormKey && oldkeyToNewkey.has(j.linkFormKey)) {
                    j.linkFormKey = oldkeyToNewkey.get(j.linkFormKey);
                  }
                }
                tagFormula = setTagFormula(j, tagFormula);
              });
              element.options.filterList.forEach(j => {
                if (j.filterObject !== 1 && oldkeyToNewkey.has(j.filterObject)) {
                  j.filterObject = oldkeyToNewkey.get(j.filterObject);
                }
                if (oldkeyToNewkey.has(j.filterField)) {
                  j.filterField = oldkeyToNewkey.get(j.filterField);
                }
              });
              element.options.tagFormula = tagFormula;
            }
            if (element.type === 'formulaInput' && element.options.formulaString) {
              const widget = /\$_widget_(.+?)_end\$/g;
              element.options.formulaString = element.options.formulaString.replace(widget, function(math, $1) {
                const spArr = $1.split('_');
                if (spArr.length >= 3) {
                  // 关联字段中的统计字段会把其父节点的字段进行拼接
                  const key1 = `${spArr[0]}_${spArr[1]}`;
                  const key2 = `${spArr[2]}${spArr[3] ? `_${spArr[3]}` : ''}`;
                  if (oldkeyToNewkey.has(key1)) {
                    return `$_widget_${oldkeyToNewkey.get(key1)}_${key2}_end$`;
                  }
                } else if (oldkeyToNewkey.has($1)) {
                  return `$_widget_${oldkeyToNewkey.get($1)}_end$`;
                }
                return math;
              });
            }
          });
          const formValidate = formOptions.config.formValidate || [];
          const fieldCondition = formOptions.config.fieldCondition || [];
          this.handlerValidateAndCOndition(formValidate, oldkeyToNewkey);
          this.handlerValidateAndCOndition(fieldCondition, oldkeyToNewkey);
          this.formOptions = formOptions;
          this.$refs['advancedSettingRef'].setConfigField(formOptions.list); // 设置配置相关字段
          this.$refs['advancedSettingRef'].initList(formOptions.list); // 高级设置的列表设置初始化
        }
        this.initAllWidget();
        this.$nextTick(() => {
          EventBus.$emit('freshFieldList'); // 初始化表单属性
        });
      });
    },
    // 获取流程列表，用于引用功能
    getProcessList() {
      processManagementList().then(res => {
        if (res.code === 200) {
          // 排除自己
          const list = res.data.filter(item => item.id !== this.id);
          this.customProcessList = list.filter(item => !!item.isCustom);
          this.processList = list;
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    // 获取角色组
    queryRoleGroups() {
      getRoleGroups({ page: 1, perPage: 9999 }).then(res => {
        res.code === 200 && this.$store.dispatch('setRoleGroups', res.data.items || []);
      });
    },
    // 获取BP类型
    queryBPList() {
      getBPList({ isAll: 1 }).then(res => {
        if (res.code === 200) {
          // BP类型（名字）可能相同，需要根据类型进行去重，后端需要获取类型名称而不是id
          const nameMap = new Map();
          const allBPList = res.data || [];
          const BPList = [];
          allBPList.forEach(item => {
            if (!nameMap.has(item.name)) {
              BPList.push(item);
              nameMap.set(item.name, true);
            }
          });
          this.$store.dispatch('setBPList', BPList);
        }
      });
    },
    // 固定表单指定BP审批人节点部门数据
    storeAllFixedDeptSelectFields(type) {
      if (!type && type !== 0) return;
      const deptFields = BPDepartment[type];
      this.$store.dispatch('setAllDeptFields', deptFields || []);
    },
    handlerValidateAndCOndition(data, oldkeyToNewkey) {
      data.forEach(i => {
        if (i.fieldList && i.fieldList.length) {
          i.fieldList = i.fieldList.map(j => oldkeyToNewkey.get(j)).filter(j => !!j);
        }
        if (i.filterList && i.filterList.length) {
          i.filterList.forEach(filter => {
            filter.filterField = oldkeyToNewkey.get(filter.filterField);
            if (filter.valueType === 1 && filter.value && oldkeyToNewkey.get(filter.value)) {
              filter.value = oldkeyToNewkey.get(filter.value);
            }
          });
        }
        if (i.frontFilterList && i.frontFilterList.length) {
          i.frontFilterList.forEach(filter => {
            filter.filterField = oldkeyToNewkey.get(filter.filterField);
            if (filter.valueType === 1 && filter.value && oldkeyToNewkey.get(filter.value)) {
              filter.value = oldkeyToNewkey.get(filter.value);
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.box-shadow {
  box-shadow: 2px 0 6px 0 rgba(207,212,221,0.81);
  z-index: 1;
  position: relative;
}
.preview-btn-style {
  background-color: #fff;
  border-color: #406eff;
  color: #406eff;
}
.right-box {
  justify-content: flex-end;
}
.save-info {
  margin-right: 16px;
  font-size: 12px;
  color: #999;
  text-align: right;
  p {
    margin: 0;
    white-space: nowrap;
  }
}
.create-container {
  .create-content{
    background-color: #fff;
    min-height: calc(100vh - 80px);
    display: flex;
    .container {
      flex:1;
      max-width: 100%;
    }
  }
  &::v-deep {
    .table-list-tabs-content-flex {
      width: 70% !important;
      display: flex;
      justify-content: center;
    }
  }
}
.back-btn {
  display: flex;
  align-items: center;
  color: #333;
  cursor: pointer;
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  .icon {
    font-size: 20px;
  }
  .text {
    max-width: 230px;
    font-size: 14px;
    white-space: nowrap;
  }
  &:hover {
    color: #406eff;
  }
}
</style>
